import api from './api';

interface User {
  userId: string;
  userName: string;
  userIcon: string;
  account: string;
  createUser: string;
  createTime: string;
}

interface Team {
  teamId: string;
  teamName: string;
  teamIcon: string;
  teamDesc: string;
  type: 'OWNER' | 'PARTICIPANT';
}

interface Project {
  projectId: string;
  projectName: string;
  projectIcon: string;
  projectDesc: string;
  type: 'OWNER' | 'PARTICIPANT';
}

interface UserInfoResponse {
  success: boolean;
  code: number;
  message: string;
  localizedMsg: string;
  data: {
    userId: string;
    userName: string;
    userIcon: string;
    account: string;
    createUser: string | null;
    createTime: string;
    teamList: Team[];
    projectList: Project[];
  };
}

interface AddTeamResponse {
  success: boolean;
  code: number;
  message: string;
  localizedMsg: string;
  data: null;
}

interface AddProjectResponse {
  success: boolean;
  code: number;
  message: string;
  localizedMsg: string;
  data: null;
}

const UserService = {
  login: async (data: { account: string; password: string }) => {
    try {
      const res = await api({
        url: '/doc/user/login',
        method: 'post', // 明确指定方法
        data,
        timeout: 5000,
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
      });
      
      console.log('登录响应:', res);
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      // 处理用户提供的响应格式
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '登录失败，请检查账号密码';
        throw new Error(errorMsg);
      }
      
      if (res.data?.token) {
        localStorage.setItem('token', res.data.token);
        console.log('Token已存储');
      } else {
        throw new Error('登录成功但未收到token');
      }
      
      return {
        success: true,
        token: res.data.token,
        ...res
      };
    } catch (error: any) {
      console.error('登录错误详情:', {
        error: error,
        message: error.message,
        stack: error.stack,
        isCorsError: error.isCorsError
      });

      let errorMessage = '登录失败';
      if (error.isCorsError) {
        errorMessage = `跨域请求被阻止，请联系管理员检查服务器CORS配置：
        
1. 确保服务器允许来自 ${window.location.origin} 的请求
2. 服务器需要配置以下响应头:
   - Access-Control-Allow-Origin: ${window.location.origin}
   - Access-Control-Allow-Methods: POST, OPTIONS
   - Access-Control-Allow-Headers: Content-Type, Authorization
3. 服务器需要正确处理OPTIONS预检请求`;
      } else if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请检查网络连接';
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      } else if (error.request) {
        errorMessage = `无法连接到服务器(${api.defaults.baseURL})，请检查：
1. 网络连接
2. 服务器地址是否正确
3. 服务器是否运行正常`;
      } else {
        errorMessage = error.message || '登录过程中发生未知错误';
      }

      throw new Error(errorMessage);
    }
  },

  // 获取用户信息接口（带重试机制）
  getUserInfo: async () => {
    try {
      const res = await api<UserInfoResponse>({
        url: '/doc/user/userInfo',
        method: 'post',
        timeout: 8000,
        data: {}
      });
      
      console.log('用户信息响应:', res);
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '获取用户信息失败';
        throw new Error(errorMsg);
      }
      
      return res.data;
    } catch (error: any) {
      console.error('获取用户信息错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '获取用户信息失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})，请检查：
1. 网络连接
2. 服务器地址是否正确
3. 服务器是否运行正常`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置允许来自 ${window.location.origin} 的请求，并支持OPTIONS预检请求。
        
解决方案:
1. 联系后端开发人员检查服务器CORS配置
2. 确保服务器响应中包含以下头信息:
   - Access-Control-Allow-Origin: ${window.location.origin}
   - Access-Control-Allow-Methods: POST, OPTIONS
   - Access-Control-Allow-Headers: Authorization, Content-Type`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },
  
  getProfile: () => api({
    url: '/user/profile',
    method: 'post'
  }),
  
  updateProfile: (data: any) => api({
    url: '/user/profile',
    method: 'post',
    data
  }),
  
  createUser: (data: {
    userName: string;
    userIcon: string;
    account: string;
    password: string;
  }) => api({
    url: '/user',
    method: 'post',
    data
  }),
  
  addUser: async (data: {
    userName: string;
    userIcon: string;
    account: string;
    password: string;
  }) => {
    try {
      const res = await api({
        url: '/doc/user/addUser',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '添加用户失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        data: res.data,
        ...res
      };
    } catch (error: any) {
      console.error('添加用户错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '添加用户失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },
  
  getUsers: () => api<User[]>({
    url: '/user/list',
    method: 'post'
  }),
  
  updateUser: (userId: string, data: Partial<User>) => 
    api({
      url: `/user/${userId}`,
      method: 'post',
      data
    }),
    
  deleteUser: (userId: string) => api({
    url: `/user/${userId}`,
    method: 'post'
  }),

  getTeamCandidateUsers: (teamId: string) => 
    api<User[]>({
      url: `/team/${teamId}/candidates`,
      method: 'post'
    }),

  // 获取团队成员
  getTeamMembers: async (teamId: string) => {
    try {
      const res = await api({
        url: '/doc/teamuser/pageUserByTeamId',
        method: 'post',
        data: { teamId },
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '获取团队成员失败';
        throw new Error(errorMsg);
      }
      
      return res.data?.records || [];
    } catch (error: any) {
      console.error('获取团队成员错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '获取团队成员失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 获取项目成员
  getProjectMembers: async (projectId: string) => {
    try {
      const res = await api({
        url: '/doc/projectuser/getUserByProjectId',
        method: 'post',
        data: { projectId },
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '获取项目成员失败';
        throw new Error(errorMsg);
      }
      
      return res.data || [];
    } catch (error: any) {
      console.error('获取项目成员错误:', error);
      throw new Error(error.message || '获取项目成员失败');
    }
  },

  // 添加项目成员
  addProjectUser: async (data: {
    projectUserList: Array<{
      projectId: string;
      userId: string;
      permission: 'r' | 'rw';
    }>;
  }) => {
    try {
      const res = await api({
        url: '/doc/projectuser/addProjectUser',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '添加项目成员失败';
        throw new Error(errorMsg);
      }
      
      return res;
    } catch (error: any) {
      console.error('添加项目成员错误:', error);
      throw new Error(error.message || '添加项目成员失败');
    }
  },

  // 删除项目成员
  deleteProjectUser: async (data: {
    projectUserList: Array<{
      projectId: string;
      userId: string;
    }>;
  }) => {
    try {
      const res = await api({
        url: '/doc/projectuser/deleteProjectUser',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '删除项目成员失败';
        throw new Error(errorMsg);
      }
      
      return res;
    } catch (error: any) {
      console.error('删除项目成员错误:', error);
      throw new Error(error.message || '删除项目成员失败');
    }
  },

  // 更新项目成员权限
  updateProjectPermission: async (data: {
    projectId: string;
    userId: string;
    permission: 'r' | 'rw';
  }) => {
    try {
      const res = await api({
        url: '/doc/projectuser/updatePermission',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '更新权限失败';
        throw new Error(errorMsg);
      }
      
      return res;
    } catch (error: any) {
      console.error('更新权限错误:', error);
      throw new Error(error.message || '更新权限失败');
    }
  },

  // 刷新用户信息
  refreshUserInfo: async () => {
    try {
      const res = await this.getUserInfo();
      return res;
    } catch (error) {
      console.error('刷新用户信息失败:', error);
      throw error;
    }
  },

  // 新增创建团队接口
  addTeam: async (data: {
    teamName: string;
    teamIcon: string;
    teamDesc: string;
  }) => {
    try {
      const res = await api<AddTeamResponse>({
        url: '/doc/team/addTeam',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '创建团队失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        ...res
      };
    } catch (error: any) {
      console.error('创建团队错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '创建团队失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 编辑团队接口
  editTeam: async (data: {
    teamId: string;
    teamName: string;
    teamDesc: string;
  }) => {
    try {
      const res = await api({
        url: '/doc/team/editTeam',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '编辑团队失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        ...res
      };
    } catch (error: any) {
      console.error('编辑团队错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '编辑团队失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 删除团队接口
  deleteTeam: async (data: {
    teamId: string;
  }) => {
    try {
      const res = await api<AddTeamResponse>({
        url: '/doc/team/deleteTeam',
        method: 'post',
        data,
        timeout: 5000
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '删除团队失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        ...res
      };
    } catch (error: any) {
      console.error('删除团队错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '删除团队失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 新增创建项目接口
  addProject: async (data: {
    teamId: string;
    projectName: string;
    projectIcon: string;
    projectDesc: string;
  }) => {
    try {
      console.log('开始调用创建项目接口', data);
      const res = await api<AddProjectResponse>({
        url: '/doc/project/addProject',
        method: 'post',
        data: {
          teamId: data.teamId,
          projectName: data.projectName,
          projectIcon: data.projectIcon,
          projectDesc: data.projectDesc
        },
        timeout: 5000,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': localStorage.getItem('token') || ''
        }
      });
      
      console.log('创建项目接口响应:', res);
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '创建项目失败';
        throw new Error(errorMsg);
      }
      
      return res;
    } catch (error: any) {
      console.error('创建项目错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '创建项目失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS，允许来自 ${window.location.origin} 的请求`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }

  },

  logout: async () => {
    try {
      const res = await api({
        url: '/doc/user/logout',
        method: 'post',
        timeout: 5000,
        headers: {
          'Authorization': localStorage.getItem('token') || ''
        }
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '退出登录失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        ...res
      };
    } catch (error: any) {
      console.error('退出登录错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '退出登录失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 编辑项目接口
  editProject: async (data: {
    projectId: string;
    projectName: string;
    projectIcon: string;
    projectDesc: string;
  }) => {
    try {
      const res = await api({
        url: '/doc/project/editProject',
        method: 'post',
        data: {
          projectId: data.projectId,
          projectName: data.projectName,
          projectIcon: data.projectIcon,
          projectDesc: data.projectDesc
        },
        timeout: 5000,
        headers: {
          'Authorization': localStorage.getItem('token') || '',
          'Content-Type': 'application/json'
        }
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '编辑项目失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        data: res.data,
        ...res
      };
    } catch (error: any) {
      console.error('编辑项目错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '编辑项目失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 添加团队成员接口
  addTeamUser: async (data: {
    teamUserList: Array<{
      userId: string;
      teamId: string;
    }>;
  }) => {
    try {
      const res = await api({
        url: '/doc/teamuser/addTeamUser',
        method: 'post',
        data,
        timeout: 5000,
        headers: {
          'Authorization': localStorage.getItem('token') || '',
          'Content-Type': 'application/json'
        }
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '添加团队成员失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        data: res.data,
        ...res
      };
    } catch (error: any) {
      console.error('添加团队成员错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '添加团队成员失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 删除团队成员接口
  deleteTeamUser: async (data: {
    teamUserList: Array<{
      userId: string;
      teamId: string;
    }>;
  }) => {
    try {
      const res = await api({
        url: '/doc/teamuser/deleteTeamUser',
        method: 'post',
        data,
        timeout: 5000,
        headers: {
          'Authorization': localStorage.getItem('token') || '',
          'Content-Type': 'application/json'
        }
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '删除团队成员失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        data: res.data,
        ...res
      };
    } catch (error: any) {
      console.error('删除团队成员错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '删除团队成员失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }

  },

  // 删除项目接口
  deleteProject: async (data: {
    projectId: string;
  }) => {
    try {
      const res = await api({
        url: '/doc/project/deleteProject',
        method: 'post',
        data,
        timeout: 5000,
        headers: {
          'Authorization': localStorage.getItem('token') || '',
          'Content-Type': 'application/json'
        }
      });
      
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '删除项目失败';
        throw new Error(errorMsg);
      }
      
      return {
        success: true,
        data: res.data,
        ...res
      };
    } catch (error: any) {
      console.error('删除项目错误:', {
        error: error,
        message: error.message,
        config: error.config,
        isCorsError: error.isCorsError
      });
      
      let errorMessage = '删除项目失败';
      if (error.isNetworkError) {
        errorMessage = `网络连接问题: 无法连接到服务器(${api.defaults.baseURL})`;
      } else if (error.isCorsError) {
        errorMessage = `跨域问题: 请确保服务器已配置CORS`;
      } else if (error.response) {
        errorMessage = error.response.data?.message || 
                      `服务器错误 (${error.response.status})`;
      }
      
      throw new Error(errorMessage);
    }
  },

  // 通过 teamId 获取团队下的项目列表
  getProjectListByTeamId: async (teamId: string) => {
    try {
      const res = await api({
        url: '/doc/user/getProjectListByUserIdOrTeamId',
        method: 'post',
        data: { teamId },
        timeout: 5000
      });
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '获取项目列表失败';
        throw new Error(errorMsg);
      }
      return res.data;
    } catch (error: any) {
      console.error('获取项目列表错误:', error);
      throw new Error(error.message || '获取项目列表失败');
    }
  },

  // 设置默认团队
  setDefaultTeam: async (teamId: string) => {
    try {
      const res = await api({
        url: '/doc/teamuser/setDefaultTeam',
        method: 'post',
        data: { teamId },
        timeout: 5000
      });
      if (!res) {
        throw new Error('未收到服务器响应');
      }
      if (res.code !== 200 || !res.success) {
        const errorMsg = res.message || res.localizedMsg || '设置默认团队失败';
        throw new Error(errorMsg);
      }
      return res;
    } catch (error: any) {
      console.error('设置默认团队错误:', error);
      throw new Error(error.message || '设置默认团队失败');
    }
  },
};

export default UserService;